/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/DB/MySQL/MySQLSqlConnection.h"


namespace Shared {
namespace DB {
namespace MySQL {

    bool MySQLSqlConnection::open(const std::string &host,
        const std::string &port, const std::string &user, 
        const std::string &pass, const std::string &db, 
        bool autoReconnect /*= true*/)
    {
        _my = mysql_init(NULL);

        do
        {
            int _port;
            const char* unix_socket;

            mysql_options(_my, MYSQL_SET_CHARSET_NAME, "utf8");
            mysql_options(_my, MYSQL_OPT_RECONNECT, "1");

            if (host == ".")
            {
                unsigned int opt = MYSQL_PROTOCOL_PIPE;
                mysql_options(_my, MYSQL_OPT_PROTOCOL, &opt);
                _port = 0;
                unix_socket = NULL;
            }
            else
            {
                _port = atoi(port.c_str());
                unix_socket = NULL;
            }


            if (autoReconnect) {
                char value = 1;
                mysql_options(_my, MYSQL_OPT_RECONNECT, &value);
            }

            if (!mysql_real_connect(_my, host.c_str(), user.c_str(),
                pass.c_str(), db.c_str(), _port, unix_socket, 0))
            {
                _errCode = mysql_errno(_my);
                _errString = mysql_error(_my);
                mysql_close(_my);
                _my = NULL;
                break;
            }

        } while (false);

        return _my != NULL;
    }

}}}